package com.study.flink.batch;

import org.apache.commons.io.FileUtils;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.MapOperator;
import org.apache.flink.configuration.Configuration;

import java.io.File;
import java.util.List;

/**
 * Distributed Cache
 *
 * @author stephen
 * @create 2019-01-28 21:05
 * @since 1.0.0
 */
public class BatchDemoDisCache {

    public static void main(String[] args) throws Exception {
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        // 注册文件
        env.registerCachedFile("/Users/stephen/weather.data", "weather");

        DataSource<String> data = env.fromElements("x", "y");

        MapOperator<String, String> result = data.map(new RichMapFunction<String, String>() {

            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);

                // 使用文件
                File weather = getRuntimeContext().getDistributedCache().getFile("weather");
                List<String> lines = FileUtils.readLines(weather);
                for (String line : lines) {
                    System.out.println(line);
                }
            }

            @Override
            public String map(String value) throws Exception {
                return value;
            }
        });

        result.print();

    }
}
